<?php

namespace Muyuxuanpay\file;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\Writer\GifWriter;
use Endroid\QrCode\Writer\PngWriter;

class MuFile
{
    /**
     * 获取文件后缀
     * @param string|null $filePath
     * @return false|mixed|string
     */
    public static function getFileSuffix(?string $filePath){
        if(empty($filePath)){
            return '';
        }
        $arr = explode('.', $filePath);
        if(count($arr) < 2){
            return '';
        }
        return end($arr);
    }

    /**
     * 文件转base64
     * @param string $filePath
     * @return string
     */
    public static function fileToBase64(?string $filePath){
        if (empty($filePath)){
            return '';
        }
        $file = file_get_contents($filePath);
        return base64_encode($file);
    }

    /**
     * base64转文件
     * @param string|null $base64_string
     * @param string|null $filePath
     * @return string|null
     * @throws \Exception
     */
    public static function base64ToFile(?string $base64_string,?string $filePath)
    {
        if(!$base64_string){
            return '';
        }
        if(!$filePath){
            return '';
        }
        // 可选：检查是否包含 data:image 前缀，并提取纯 base64 数据
        if (preg_match('/^data:image\/(\w+);base64,/', $base64_string, $matches)) {
            $image_type = $matches[1]; // 如 png, jpeg
            $base64_data = substr($base64_string, strpos($base64_string, ',') + 1);
        } else {
            // 如果没有前缀，假设它就是纯 base64 图像数据
            $image_type = 'png'; // 默认类型，你可以根据实际情况修改
            $base64_data = $base64_string;
        }

// 解码 base64 数据
        $image_binary = base64_decode($base64_data);

        if ($image_binary === false) {
            throw new \Exception('解码失败');
        }

// 定义保存的图片文件名，根据类型设置扩展名
        $extension = $image_type === 'jpeg' || $image_type === 'jpg' ? 'jpg' : $image_type;
        $dir = dirname($filePath);
        if(!is_dir($dir)){
            @mkdir($dir, 0755, true);
        }
        if($dir==$filePath){
            $time = time();
            $filePath = rtrim($filePath, '/')."/{$time}.".$extension;
        }
        file_put_contents($filePath, $image_binary);
        return $filePath;
    }

    /**
     * 图片压缩(质量)
     * @param string $sourcePath   原图路径
     * @param string $destinationPath 压缩后图片路径
     * @param float $quality  压缩比例
     * @return bool
     */
    public static function compressImage($sourcePath, $destinationPath, $quality){
        $imageInfo = getimagesize($sourcePath);
        $imageType = $imageInfo[2];

        if ($imageType == IMAGETYPE_JPEG) {
            $image = imagecreatefromjpeg($sourcePath);
            imagejpeg($image, $destinationPath, $quality);
        } elseif ($imageType == IMAGETYPE_PNG) {
            $image = imagecreatefrompng($sourcePath);
            imagepng($image, $destinationPath, 9 - round($quality * 0.08));
        } elseif ($imageType == IMAGETYPE_GIF) {
            $image = imagecreatefromgif($sourcePath);
            imagegif($image, $destinationPath);
        }
        return imagedestroy($image);
    }

    /**
     * 图片压缩(宽度、高度)
     * @param string $sourcePath  图片地址
     * @param string $destinationPath 压缩后地址
     * @param float|array $quality 压缩比例（数组必须有宽高或者其中之一,width,height）
     * @return bool
     * @throws \Exception
     */
    public static function compressImageWidthHeight($sourcePath, $destinationPath,$quality=null){
        $imageInfo = getimagesize($sourcePath);
        if(empty($quality)){
            $newWidth = $imageInfo[0];
            $newHeight = $imageInfo[1];
        }else{
            if(is_numeric($quality)){
                $newWidth = $imageInfo[0]*floatval($quality);
                $newHeight = $imageInfo[1]*floatval($quality);
            }elseif (is_array($quality)){
                if(empty($quality['width'])||empty($quality['height'])){
                    if(!empty($quality['width'])){
                        $bili = $quality['width']/$imageInfo[0];
                    }elseif (!empty($quality['height'])){
                        $bili = $quality['height']/$imageInfo[1];
                    }elseif (empty($quality['width'])&&empty($quality['height'])){
                        throw new \Exception('参数错误');
                    }
                    $newWidth = $imageInfo[0]*$bili;
                    $newHeight = $imageInfo[1]*$bili;
                }else{
                    $newWidth = $quality['width'];
                    $newHeight =  $quality['height'];
                }
            }else{
                throw new \Exception('参数错误');
            }
        }
//        $newWidth = $imageInfo[0]*floatval($quality);
//        $newHeight = $imageInfo[1]*floatval($quality);
        $imageType = $imageInfo[2];
        // 创建一个真彩色图像
        $newImage = imagecreatetruecolor($newWidth, $newHeight);
        if ($imageType == IMAGETYPE_JPEG) {
            $sourceImage =imagecreatefromjpeg($sourcePath);
        } elseif ($imageType == IMAGETYPE_PNG) {
            $sourceImage =imagecreatefrompng($sourcePath);
        } elseif ($imageType == IMAGETYPE_GIF) {
            $sourceImage =imagecreatefromgif($sourcePath);
        }
        imagecopyresampled(
            $newImage, // 目标图像
            $sourceImage, // 源图像
            0, // 目标图像的 X 坐标
            0, // 目标图像的 Y 坐标
            0, // 源图像的 X 坐标
            0, // 源图像的 Y 坐标
            $newWidth, // 目标图像的宽度
            $newHeight, // 目标图像的高度
            imagesx($sourceImage), // 源图像的宽度
            imagesy($sourceImage) // 源图像的高度
        );
        if ($imageType == IMAGETYPE_JPEG) {
            $res = imagejpeg($newImage, $destinationPath);
        } elseif ($imageType == IMAGETYPE_PNG) {
            $res = imagepng($newImage, $destinationPath);
        } elseif ($imageType == IMAGETYPE_GIF) {
            $res = imagegif($newImage, $destinationPath);
        }
        if($res){
            imagedestroy($newImage);
        }
        return $res;
    }

    /**
     * 生成二维码
     * @param $url
     * @param $filePath
     * @param $imagType
     * @param $str_code
     * @param $size
     * @param $margin
     * @param $logoPath
     * @param $logoWidth
     * @return mixed|string|null
     * @throws \Exception
     */
    public static function codeToQrcode($url, $filePath = null, $imagType = 'png',$str_code="UTF-8",$size=300,$margin=10,$logoPath=null,$logoWidth=60)
    {
        $imagTypeNs = match ($imagType){
            'png','PNG','jpg','JPG','jpeg','JPEG'=>new PngWriter(),
            'gif','GIF'=>new GifWriter(),
            default=>new PngWriter()
        };
        if(empty($logoPath)){
            $result = Builder::create()
                ->writer($imagTypeNs)
                ->data($url)
                ->encoding(new Encoding($str_code))
                ->size($size)
                ->margin($margin)
                ->build();
        }else{
            $result = Builder::create()
                ->writer($imagTypeNs)
                ->data($url)
                ->encoding(new Encoding($str_code))
                ->size($size)
                ->margin($margin)
//                ->roundBlockSizeMode(RoundBlockSizeMode::MEDIUM)
                ->logoPath($logoPath)
//                ->logoRoundedCorner($logoRund)
                ->logoResizeToWidth($logoWidth)
                ->build();
        }
        if(empty($filePath)){
            header('Content-Type: ' . $result->getMimeType());
            return $result->getString();
        }
        $dir = dirname($filePath);
        if(!is_dir($dir)){
            @mkdir($dir,0777,true);
        }
        if($dir==$filePath){
            $filePath = rtrim($filePath,'/\\').'/'.time().'.'.$imagType;
        }
        file_put_contents($filePath, $result->getString());
        return $filePath;
    }
}